package com.aqie.safe.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author: aqie
 * @create: 2020-12-21 20:16
 **/
@Slf4j
@RequiredArgsConstructor
@EnableWebSecurity(debug = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // super.configure(http);
        http
                .csrf(Customizer.withDefaults())
                .httpBasic(Customizer.withDefaults())
                .formLogin(form -> form.loginPage("/login")
                            .usernameParameter("username1")  // 定制username

                            .permitAll()) // 防止重定向
                .logout(logout -> logout.logoutUrl("/logout"))
                .rememberMe(rememberMe -> rememberMe.tokenValiditySeconds(30 * 24 *3600).rememberMeCookieName("someKeyForRemember"))
                // .authorizeRequests(req -> req.antMatchers("/api/**").authenticated());
                .authorizeRequests(req -> req.anyRequest().authenticated());
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password(passwordEncoder().encode("12345678"))
                .roles("USER", "ADMIN");
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        /**
         * js css 图片 图标 静态资源
         */
        web.ignoring().mvcMatchers("/public/**")
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations());
    }
}
